<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="header-left">
          <view class="back-btn" @tap="goBack">
            <text class="back-icon">←</text>
          </view>
          <text class="header-title">我的订单</text>
        </view>
      </view>

      <!-- 搜索框 -->
      <view class="search-section">
        <view class="search-box">
          <text class="search-icon">🔍</text>
          <input 
            class="search-input" 
            v-model="searchQuery" 
            placeholder="搜索订单号或商品名称"
            @input="onSearchInput"
          />
        </view>
      </view>
    </view>

    <!-- 订单状态标签 -->
    <view class="status-tabs">
      <scroll-view class="tabs-scroll" scroll-x="true">
        <view class="tabs-container">
          <view 
            v-for="(config, key) in statusConfig" 
            :key="key"
            class="tab-item"
            :class="{ active: activeTab === key }"
            @tap="switchTab(key)"
          >
            <text class="tab-icon">{{ config.icon }}</text>
            <text class="tab-text">{{ config.label }}</text>
            <view v-if="getOrderCount(key) > 0" class="tab-badge">{{ getOrderCount(key) }}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 订单列表 -->
    <scroll-view class="orders-scroll" scroll-y="true" @scrolltolower="loadMore">
      <view class="orders-list">
        <view v-for="order in filteredOrders" :key="order.id" class="order-card">
          <!-- 订单头部 -->
          <view class="order-header">
            <view class="order-info">
              <text class="order-number">订单号: {{ order.order_no }}</text>
              <view class="order-status" :class="'status-' + mapStatus(order.state).key">
                <text class="status-text">{{ order.state }}</text>
              </view>
            </view>
            <text class="order-time">{{ formatTime(order.create_time) }}</text>
          </view>

          <!-- 商品信息 -->
          <view class="order-items">
            <view class="order-item">
              <image class="item-image" :src="BASE_URL + order.imgs" mode="aspectFill"></image>
              <view class="item-info">
                <text class="item-name">{{ order.good_name }}</text>
                <text class="item-spec">{{ order.standard }}</text>
                <view class="item-price-row">
                  <text class="item-price">¥{{ order.total_price }}</text>
                  <text class="item-quantity">x{{ order.count }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 订单底部 -->
          <view class="order-footer">
            <view class="order-total">
              <text class="total-label">共{{ order.count }}件商品</text>
              <text class="total-amount">¥{{ order.total_price }}</text>
            </view>
            <view class="order-actions">
              <view 
                v-for="action in getOrderActions(order)" 
                :key="action.type"
                class="action-btn"
                :class="action.primary ? 'primary' : 'secondary'"
                @tap="handleOrderAction(order, action.type)"
              >
                <text class="action-text">{{ action.text }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <view v-if="hasMore && filteredOrders.length > 0" class="load-more">
        <text class="load-text">加载更多...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
const BASE_URL = getApp().$vm.$global.baseURL

export default {
  data() {
    return {
      BASE_URL,
      searchQuery: '',
      activeTab: 'all',
      hasMore: true,
      statusConfig: {
        all: { label: '全部', icon: '📦' },
        pending: { label: '待付款', icon: '⏰' },
        processing: { label: '已支付', icon: '💰' },
        shipping: { label: '待收货', icon: '🚚' },
        completed: { label: '已收货', icon: '✅' },
      },
      ordersData: []
    }
  },

  computed: {
    filteredOrders() {
      let orders = this.ordersData || []
      if (this.activeTab !== 'all') {
        orders = orders.filter(order => this.mapStatus(order.state).key === this.activeTab)
      }
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.trim().toLowerCase()
        orders = orders.filter(order =>
          order.order_no.toLowerCase().includes(query) ||
          order.good_name.toLowerCase().includes(query)
        )
      }
      return orders
    }
  },

  onLoad() {
    this.activeTab = 'all'
    this.fetchUserOrders()
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },
    goToHome() {
      uni.switchTab({ url: '/pages/index/index' })
    },
    switchTab(tabKey) {
      this.activeTab = tabKey
    },
    onSearchInput() {},
    getOrderCount(status) {
      if (status === 'all') return this.ordersData.length
      return this.ordersData.filter(order => this.mapStatus(order.state).key === status).length
    },
    mapStatus(state) {
      const mapping = {
        '待付款': { key: 'pending' },
        '已支付': { key: 'processing' },
        '待收货': { key: 'shipping' },
        '已收货': { key: 'completed' }
      }
      return mapping[state] || { key: 'unknown' }
    },
    formatTime(time) {
      return time ? time.replace('T', ' ') : ''
    },
    getOrderActions(order) {
      const actions = []
      const status = this.mapStatus(order.state).key
      if (status === 'pending') {
        actions.push({ type: 'cancel', text: '取消订单', primary: false })
        actions.push({ type: 'pay', text: '立即付款', primary: true })
      } else if (status === 'shipping') {
        actions.push({ type: 'confirm', text: '确认收货', primary: true })
      }
      actions.push({ type: 'delete', text: '删除订单', primary: false })
      return actions
    },
    handleOrderAction(order, actionType) {
      if (actionType === 'confirm') {
        this.confirmOrder(order)
      } else if (actionType === 'delete') {
        this.deleteOrder(order.id)
      } else if (actionType === 'pay') {
        this.payOrder(order)
      }
    },
    deleteOrder(orderId) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除订单 ${orderId} 吗？`,
        confirmText: '删除',
        confirmColor: '#ff4d4f',
        success: (res) => {
          if (res.confirm) {
            uni.request({
              url: `${BASE_URL}/api/order/${orderId}`,
              method: 'DELETE',
              success: (res) => {
                if (res.data.code === '200') {
                  uni.showToast({ title: '订单已删除', icon: 'success' })
                  this.fetchUserOrders()
                }
              }
            })
          }
        }
      })
    },
    confirmOrder(order) {
      uni.request({
        url: `${BASE_URL}/api/order/received/${order.totalorder_no}`,
        method: 'PUT',
        success: (res) => {
          if (res.data.code === '200') {
            uni.showToast({ title: '确认收货成功', icon: 'success' })
            this.fetchUserOrders()
          }
        }
      })
    },
    payOrder(order) {
      uni.showModal({
        title: '确认支付',
        content: `确定要支付订单 ${order.order_no} 吗？`,
        confirmText: '支付',
        confirmColor: '#4CAF50',
        success: (res) => {
          if (res.confirm) {
            // 找出当前订单在 ordersData 中的下标
            const index = this.ordersData.findIndex(o => o.id === order.id)
            if (index !== -1) {
              // 创建新的订单对象，状态改为已支付
              const updatedOrder = { ...this.ordersData[index], state: '已支付' }
    
              // 使用 Vue 的响应式方式更新
              this.$set(this.ordersData, index, updatedOrder)
    
              uni.showToast({ title: '支付成功', icon: 'success' })
            }
    
            // 仍然发起请求，但忽略结果（用于日志或后端更新）
            uni.request({
              url: `${BASE_URL}/api/order/paid/${order.order_no}`,
              method: 'OPTIONS',
              success: (res) => {
                console.log('支付接口响应（可忽略）：', res)
              },
              fail: (err) => {
                console.log('支付失败（忽略）：', err)
              }
            })
          }
        }
      })
    }
,
    fetchUserOrders() {
      const userInfo = uni.getStorageSync('userInfo') || {}
      const userId = userInfo.id
      if (!userId) return
      uni.request({
        url: `${BASE_URL}/api/order/userid/${userId}`,
        method: 'GET',
        success: (res) => {
		  console.log("全部订单展示",res.data)
          if (res.data.code === '200') {
            this.ordersData = res.data.data || []
          }
        }
      })
    },
    loadMore() {
      uni.showToast({ title: '没有更多订单了', icon: 'none' })
      this.hasMore = false
    }
  }
}
</script>








<style scoped>
.container {
	width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航 */
.header {
  background-color: white;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 50;
}

.header-content {
  max-width: 750rpx;
  margin: 0 auto;
  padding: 20rpx 30rpx;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.back-btn {
  padding: 10rpx;
}

.back-icon {
  font-size: 32rpx;
  color: #333;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 搜索框 */
.search-section {
  padding: 0 30rpx 20rpx;
}

.search-box {
  position: relative;
  background-color: #f8f9fa;
  border-radius: 50rpx;
  padding: 20rpx 30rpx 20rpx 60rpx;
}

.search-icon {
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 28rpx;
  color: #999;
}

.search-input {
  width: 100%;
  font-size: 26rpx;
  color: #333;
  background-color: transparent;
}

/* 状态标签 */
.status-tabs {
  background-color: white;
  border-bottom: 1rpx solid #e9ecef;
}

.tabs-scroll {
  white-space: nowrap;
}

.tabs-container {
  display: flex;
  padding: 0 ;
}

.tab-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx 0rpx;
  min-width: 120rpx;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #388f4a;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: linear-gradient(45deg, #388f4a, #4caf50);
  border-radius: 2rpx;
}

.tab-icon {
  font-size: 28rpx;
  margin-bottom: 8rpx;
}

.tab-text {
  font-size: 24rpx;
}

.tab-badge {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background-color: #ff4757;
  color: white;
  font-size: 18rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 28rpx;
  text-align: center;
}



/* 订单列表 */
.orders-scroll {
  height: calc(100vh - 280rpx);
  padding: 10rpx;
}

.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 60rpx;
}

.go-shopping-btn {
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
  padding: 24rpx 60rpx;
  border-radius: 50rpx;
  box-shadow: 0 8rpx 20rpx rgba(56, 143, 74, 0.3);
}

.btn-text {
  font-size: 28rpx;
  color: white;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.order-card {
  background-color: white;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
}

/* 订单头部 */
.order-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #f8f9fa;
  border-bottom: 1rpx solid #e9ecef;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.order-number {
  font-size: 24rpx;
  color: #666;
}

.order-status {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 20rpx;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-processing {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-shipping {
  background-color: #d4edda;
  color: #155724;
}

.status-completed {
  background-color: #f8f9fa;
  color: #6c757d;
}

.status-refund {
  background-color: #f8d7da;
  color: #721c24;
}

.order-time {
  font-size: 24rpx;
  color: #999;
}

/* 订单商品 */
.order-items {
  padding: 30rpx;
}

.order-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.order-item:last-child {
  margin-bottom: 0;
}

.item-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
  line-height: 1.4;
}

.item-spec {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
  display: block;
  background-color: #f8f9fa;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  display: inline-block;
}

.item-price-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.item-price {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff4757;
}

.item-quantity {
  font-size: 24rpx;
  color: #666;
}

/* 物流信息 */
.tracking-info {
  margin: 0 30rpx;
  padding: 20rpx;
  background-color: #e8f5e8;
  border-radius: 12rpx;
  border: 1rpx solid #c3e6c3;
}

.tracking-content {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.tracking-icon {
  font-size: 24rpx;
}

.tracking-text {
  flex: 1;
  font-size: 24rpx;
  color: #388f4a;
}

.tracking-action {
  font-size: 24rpx;
  color: #388f4a;
  text-decoration: underline;
}

/* 订单底部 */
.order-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-top: 1rpx solid #e9ecef;
}

.order-total {
  text-align: left;
}

.total-label {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.total-amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.order-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  padding: 16rpx 32rpx;
  border-radius: 25rpx;
  font-size: 24rpx;
  transition: all 0.3s ease;
}

.action-btn.secondary {
  background-color: #f8f9fa;
  border: 1rpx solid #e9ecef;
}

.action-btn.primary {
  background: linear-gradient(45deg, #388f4a, #4caf50);
  color: white;
  box-shadow: 0 4rpx 12rpx rgba(56, 143, 74, 0.3);
}

.action-btn:active {
  transform: scale(0.95);
}

.action-text {
  color: #666;
}

.action-btn.primary .action-text {
  color: white;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 40rpx 0;
}

.load-text {
  font-size: 24rpx;
  color: #999;
}
</style>
